<template>
  <div>
    <el-upload
      :headers="{
        'Authorization':token
      }"
      :accept="imgType"
      class="avatar-uploader"
      :action="baseUrl+'/upload'"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
    >
      <img v-if="imgUrl" :src="imgUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
export default {
  props: {
    value: {
      type: String,
      required: true,
      default: ''
    },
    imgType: { // 可上传的图片类型，初始化是所有图片类型都能上传
      type: String,
      required: false,
      default: 'image/*'
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      token: 'Bearer ' + getToken(),
      imgUrl: this.value
    }
  },
  watch: {
    value(newVal, oldVal) {
      this.imgUrl = newVal
    }
  },
  methods: {
    handleAvatarSuccess(data) {
      const { code, url } = data
      if (code === 200) {
        this.imgUrl = url
        this.$emit('getUrl', url)
      }
    }
  }
}
</script>

<style scoped lang="scss">
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
